﻿using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

namespace QAQ
{    
    class SocClient
    {
        static GCPacket mGCPacket = null; 
        public static string mServerIp;
        public static int mServerPort;
        public static bool badass = false;
        Thread mThread;

        public SocClient(GCPacket mGCP, string ServerIpAddr, int Port)
        {
            mGCPacket = mGCP;
            mServerIp = ServerIpAddr;
            mServerPort = Port;

            mThread = new Thread(new ThreadStart(Service));
            mThread.Start();
        }
        public void Dispose(){
            mThread.Abort();
        }
        public static void Service()
        {
            TcpClient client;
            try
            {
                client = new TcpClient(mServerIp, mServerPort);
            }
            catch (Exception e)
            {
                return;
            }
            try
            {
                Stream s = client.GetStream();
                StreamReader sr = new StreamReader(s);
                StreamWriter sw = new StreamWriter(s);
                sw.AutoFlush = true;                
                while (true)
                {

                    if (true == mGCPacket.isEmpty|| false == mGCPacket.isValid())
                    {
                        sw.WriteLine("PASSWD?");
                        mGCPacket.mStringPasswd = sr.ReadLine();                        

                        sw.WriteLine("ROOMID?");
                        try
                        {
                            mGCPacket.SetId(Convert.ToInt32(sr.ReadLine()));
                        }
                        catch (Exception e)
                        {
                            continue;
                        }
                        if (true == badass)
                        {
                            badass = false;
                            sw.WriteLine("BADASS");
                        }
                    }
                }
                s.Close();
            }
            catch (Exception e)
            {
            //    MessageBox.Show(e.ToString());
                
            }
            finally
            {
                // code in finally block is guranteed 
                // to execute irrespective of 
                // whether any exception occurs or does 
                // not occur in the try block
                client.Close();
            }
        }
    }
}
